import traceback
from django.http import HttpResponse, JsonResponse
import logging
from django.utils.deprecation import MiddlewareMixin
from app.views.common import HttpError, HttpSuccess
logger = logging.getLogger('default')


class error_hander(MiddlewareMixin):
    def process_request(self, request):
        print("request")

        return None 
    def process_view(self, request, view_func,view_args,view_kwargs):
        print("process_view")
        
        return None 
    
    def process_response(self, request, res):
        try:
            if isinstance(res, JsonResponse):
                return res
            elif isinstance(res,HttpSuccess) or isinstance(res,HttpError):
                return JsonResponse(vars(res))
            else:
                logger.error(str(res))
                return JsonResponse(vars(HttpError(msg = "系统未知异常")))
        except Exception :
                logger.error(traceback.format_exc())
                return JsonResponse(vars(HttpError(msg = "系统未知异常")))


        
    def process_exception(self, request, exception):
        logger.error("接口调用失败:$s", request.path)
        logger.error(traceback.format_exc())
        return exception
    